<template>
    <div>
        <!-- 面包屑导航区 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片展示区 -->
        <el-card>
            <!-- 添加按钮区 -->
            <el-row>
                <el-col>
                    <el-button type="primary" @click="addDialogVisible=true">添加角色</el-button>
                </el-col>
            </el-row>
            <!-- 表格展示区 -->
            <el-table :data="rolesList" border stripe>
                <!-- 展开列 -->
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-row v-for="l1 in scope.row.children" :key="l1.id" class="vcenter">
                            <el-col :span="5">
                                <el-tag :key="l1.id" closable type="primary" :disable-transitions="false"
                                    @close="removeRight(scope.row, l1.id)">
                                    {{ l1.authName }}
                                </el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <el-col :span="19">
                                <el-row v-for="l2 in l1.children" :key="l2.id" class="vcenter">
                                    <el-col :span="5">
                                        <el-tag :key="l2.id" closable type="success" :disable-transitions="false"
                                            @close="removeRight(scope.row, l2.id)">
                                            {{ l2.authName }}
                                        </el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <el-col :span="18">
                                        <el-tag v-for="l3 in l2.children" :key="l3.id" closable type="warning"
                                            :disable-transitions="false" @close="removeRight(scope.row, l3.id)">
                                            {{ l3.authName }}
                                        </el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
                <!-- 索引列 -->
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column prop="roleName" label="角色名称"></el-table-column>
                <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
                <!-- 操作列 -->
                <el-table-column label="操作" width="400px">
                    <template slot-scope="scope">
                        <!-- 编辑按钮 -->
                        <el-button type="primary" icon="el-icon-edit" size="mini"
                            @click="showEditDialog(scope.row.id)">编辑</el-button>
                        <!-- 删除按钮 -->
                        <el-button type="danger" icon="el-icon-delete" size="mini"
                            @click="deleteRole(scope.row.id)">删除</el-button>
                        <!-- 分配用户角色按钮 -->
                        <el-button type="warning" icon="el-icon-setting" size="mini"
                            @click="showConfigRightDialog(scope.row)">分配权限</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <!-- 添加角色对话框 -->
        <el-dialog title="添加角色" :visible.sync="addDialogVisible" width="40%" @close="resetForm('addFormRef')">
            <el-form :model="addForm" :rules="roleFormRules" ref="addFormRef" label-width="80px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="addForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="addForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitAddForm">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 编辑用户对话框 -->
        <el-dialog title="修改角色信息" :visible.sync="editDialogVisible" width="40%" @close="resetForm('editFormRef')">
            <el-form :model="editForm" :rules="roleFormRules" ref="editFormRef" label-width="80px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="editForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="editForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitEditForm">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 分配权限对话框 -->
        <el-dialog title="分配权限" :visible.sync="configRightDialogVisible" width="40%">
            <el-tree :data="rightsList" :props="treeProps" show-checkbox node-key="id" default-expand-all ref="treeRef"
                :default-checked-keys="leafKeys">
            </el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="configRightDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="configRights">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            rolesList: [],
            rightsList: [],
            // 权限树形空间的绑定对象
            treeProps: {
                label: 'authName',
                children: 'children'
            },
            roleId: '',
            leafKeys: [],
            // 默认选中的权限
            addDialogVisible: false,
            editDialogVisible: false,
            configRightDialogVisible: false,
            addForm: {
                roleName: '',
                roleDesc: ''
            },
            editForm: {},
            roleFormRules: {
                roleName: [
                    { required: true, message: '请输入角色名称', trigger: 'blur' },
                    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
                ],
                roleDesc: [
                    { required: true, message: '请输入角色描述', trigger: 'blur' },
                    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
                ],
            },
        }
    },
    created() {
        this.getRolesList()
    },
    methods: {
        getRolesList() {
            this.$http.get('roles').then((res) => {
                // console.log(res);
                this.rolesList = res.data
            })
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        showEditDialog(id) {
            this.$http.get(`roles/${id}`).then(({ data: res }) => {
                if (res.meta.status === 200) {
                    this.editForm = res.data
                    this.editDialogVisible = true
                } else {
                    this.$message.error('无法编辑')
                }
            })
        },
        showConfigRightDialog(role) {
            this.roleId = role.id
            // 获取所有权限数据
            this.$http.get('rights/tree').then(({ data: res }) => {
                console.log(res);
                if (res.meta.status === 200) {
                    this.rightsList = res.data
                    this.leafKeys = []
                    this.getLeafKeys(role, this.leafKeys)
                }
            })
            this.configRightDialogVisible = true
        },
        // 删除角色
        deleteRole(id) {
            this.$confirm('此操作将永久删除角色,是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$http.delete(`roles/${id}`).then((res) => {
                    this.getRolesList()
                    this.$message.success(res.meta.msg)
                })
            }).catch(() => {
                this.$message.info('已取消删除')
            })
        },
        // 提交添加角色表单
        submitAddForm() {
            this.$refs.addFormRef.validate((valid) => {
                if (valid) {
                    this.$http.post('roles', this.addForm).then((res) => {
                        this.addDialogVisible = false
                        this.getRolesList()
                        this.$message.success(res.meta.msg)
                    })
                }
            })
        },
        submitEditForm() {
            this.$refs.editFormRef.validate((valid) => {
                if (valid) {
                    this.$http.put(`roles/${this.editForm.roleId}`, this.editForm).then(() => {
                        // console.log(res);
                        this.editDialogVisible = false
                        this.getRolesList()
                        this.$message.success('更新成功');
                    })
                }
            });
        },
        // 删除指定角色的权限
        removeRight(role, rightId) {
            this.$confirm('此操作将永久删除权限,是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                // console.log(role, rightId);
                this.$http.delete(`roles/${role.id}/rights/${rightId}`).then((res) => {
                    role.children = res.data
                    this.$message.success(res.meta.msg)
                })
            }).catch(() => {
                this.$message.info('已取消删除')
            })
        },
        // 获取三级权限的ID
        getLeafKeys(node, arr) {
            if (!node.children) {
                arr.push(node.id)
            } else {
                node.children.forEach(item => {
                    this.getLeafKeys(item, arr)
                });
            }
        },
        // 为角色分配权限
        configRights() {
            const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
            console.log(keys);
            const idStr = keys.join(',')
            this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr }).then((res) => {
                this.$message.success('分配权限成功')
                this.getRolesList()
                this.configRightDialogVisible = false
            })
        }
    }
}
</script>

<style scoped lang="less">
.el-table {
    /deep/ th {
        padding: 10px;
    }
    /deep/ td {
        padding: 5px;
    }
}
.el-tag {
    margin: 7px;
}

.el-table .el-row {
    border-bottom: 1px solid #eee;
}

.el-table .el-row {
    border-top: 1px solid #eee;
}

.vcenter {
    display: flex;
    align-items: center;
}
</style>